package cn.abcode.test.springbootsecurity.demo.config;

import cn.abcode.test.springbootsecurity.demo.auth.AuthenticationCustomProvider;
import cn.abcode.test.springbootsecurity.demo.auth.CustomAuthenticationDetailsSource;
import cn.abcode.test.springbootsecurity.demo.filter.LoginFilter;
import cn.abcode.test.springbootsecurity.demo.filter.VerifyCodeFilter;
import cn.abcode.test.springbootsecurity.demo.handler.AccessDeniedCustomHandler;
import cn.abcode.test.springbootsecurity.demo.handler.AuthenticationFailCustomHandler;
import cn.abcode.test.springbootsecurity.demo.jpa.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;

import java.io.PrintWriter;
import java.util.Arrays;

/**
 * 使用json格式登录
 */
@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;
    @Autowired
    VerifyCodeFilter verifyCodeFilter;
    @Autowired
    AccessDeniedCustomHandler accessDeniedCustomHandler;
    @Autowired
    AuthenticationFailCustomHandler authenticationFailCustomHandler;
    @Autowired
    CustomAuthenticationDetailsSource customAuthenticationDetailsSource;

   /* @Bean
    SessionRegistryImpl sessionRegistry() {
        return new SessionRegistryImpl();
    }
*/
    @Bean
    LoginFilter loginFilter() throws Exception{
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setAuthenticationDetailsSource(customAuthenticationDetailsSource);
        //认证成功
        loginFilter.setAuthenticationSuccessHandler((request, response, authentication)->{
            Object principal = authentication.getPrincipal();
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(new ObjectMapper().writeValueAsString(principal));
            out.flush();
            out.close();
        });
        //认证失败
        loginFilter.setAuthenticationFailureHandler((request, response, e)->{
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();

            String msg = e.getMessage();
            if (e instanceof LockedException) {
                msg = "账户被锁定，请联系管理员!";
            } else if (e instanceof CredentialsExpiredException) {
                msg = "密码过期，请联系管理员!";
            } else if (e instanceof AccountExpiredException) {
                msg = "账户过期，请联系管理员!";
            } else if (e instanceof DisabledException) {
                msg = "账户被禁用，请联系管理员!";
            } else if (e instanceof BadCredentialsException) {
                msg = "用户名或者密码输入错误，请重新输入!";
            }
            out.write(msg);
            out.flush();
            out.close();
        });
        //认证管理类
        loginFilter.setAuthenticationManager(authenticationManager());
        //
        loginFilter.setFilterProcessesUrl("/doLogin");

        /*ConcurrentSessionControlAuthenticationStrategy sessionStrategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry());
        sessionStrategy.setMaximumSessions(1);
        loginFilter.setSessionAuthenticationStrategy(sessionStrategy);*/
        return loginFilter;
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(10);
    }

    @Bean
    AuthenticationCustomProvider authenticationCustomProvider(){
        AuthenticationCustomProvider provider = new AuthenticationCustomProvider();
        provider.setPasswordEncoder(passwordEncoder());
        provider.setUserDetailsService(userService);
        return provider;
    }

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        ProviderManager manager = new ProviderManager(Arrays.asList(authenticationCustomProvider()));
        return manager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //忽略静态文件
        web.ignoring().antMatchers("/js/**", "/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("user")
                .antMatchers("/kaptcha/getCode").permitAll()
                .antMatchers("/test/create").permitAll()
                .antMatchers("/kaptcha/getCodeStr").permitAll()
                .anyRequest().authenticated()
                .and()

                //登录配置
                //.formLogin()
                //.authenticationDetailsSource(customAuthenticationDetailsSource)
                //.permitAll()

                //.and()
                //注销登录
                .logout()
                .logoutUrl("/test/logout")  //get请求
                .logoutSuccessHandler((request, response, authentication)->{
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter out = response.getWriter();
                    out.write("注销成功");
                    out.flush();
                    out.close();
                })
                .deleteCookies()   //清除cookie
                .clearAuthentication(true)      //清除认证信息(默认值为true)
                .invalidateHttpSession(true)    //设置HttpSession失效(默认值为true)
                .permitAll()
                .and()
                .csrf().disable().exceptionHandling()
                //未认证时的处理
                .authenticationEntryPoint(authenticationFailCustomHandler)
                //无权限时的处理
                .accessDeniedHandler(accessDeniedCustomHandler)

                ;
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
